package uk.co.entropedia.display
{
	import com.bit101.components.Component;
	import com.bit101.components.TextArea;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.utils.getQualifiedClassName;
	
	import mx.utils.StringUtil;
	
	public class ComponentStructure extends TextArea
	{
		protected var scroll : int = 0;
		
		public function ComponentStructure(parent:DisplayObjectContainer=null, xpos:Number=0, ypos:Number=0)
		{
			super(parent, xpos, ypos );
			editable = false;
			html = true;
			this._tf.condenseWhite = false;
			selectable = true;
			
			
		}
		
		public static function getContainerComponents( parent : DisplayObjectContainer, indent : int = 0, selected : Component = null ):String
		{
			var out : String = '';
			var isSelectedPath : Boolean = selected && ( parent==selected || parent.contains( selected ) );
			
			var className : String = getQualifiedClassName(parent);
			className = className.substr( className.lastIndexOf(':')+1 );
			
			if( parent is Component && Component(parent).tag >= 0 )
			{
				var isContainerComponent : Boolean = DialogComponent.isContainerComponent( parent );
				var isSelected : Boolean = selected == parent;
				var isUserCreatedComponent : Boolean = DialogComponent.isComponent( parent );
				
				var tag : int = Component( parent ).tag;
				if( isContainerComponent && isSelected  )			out += '<a href="event:'+tag+'">'+StringUtil.repeat(' ',indent)+'+ <u>'+ parent.name +' ('+className+')</u></a>\n' ;
				else if( isContainerComponent && isSelectedPath ) 	out += '<a href="event:'+tag+'">'+StringUtil.repeat(' ',indent)+'- '+parent.name +' ('+className+')</a>\n' ;
				else if( isContainerComponent )						out += '<a href="event:'+tag+'">'+StringUtil.repeat(' ',indent)+'+ '+ parent.name +' ('+className+')</a>\n' ;
				else if( isSelected )								out += '<a href="event:'+tag+'">'+StringUtil.repeat(' ',indent)+' <u>'+parent.name +' ('+className+')</u></a>\n' ;
				else if( isUserCreatedComponent )					out += '<a href="event:'+tag+'">'+StringUtil.repeat(' ',indent)+' '+ parent.name +' ('+className+')</a>\n' ;
			}
			
			if( parent is Component ) indent++;
			
			if( isSelectedPath || !isUserCreatedComponent )
				for( var i : int = 0 ; i < parent.numChildren ; i++ )
				{
					var d : DisplayObject = parent.getChildAt( i );
					if( d is DisplayObjectContainer )
					{
						out += getContainerComponents( d as DisplayObjectContainer, indent, selected );
					}
				}
			
			return out;
		}
		
		public function update( top : DisplayObjectContainer, selected : Component = null ):void
		{
			scroll = _tf.scrollV;
			text = getContainerComponents( top, 0, selected );	
		}
		
		public override function draw():void
		{
			super.draw();
			if( scroll > 0 )
			{
				_tf.scrollV = scroll;
				updateScrollbar();
				scroll = 0;
			}
			
		}
		
	}
}